import { nanoid } from 'nanoid'
import React, { Component } from 'react'
import './App.css'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'

export default class App extends Component {
    state = {
        todos: [
            {
                id: nanoid(),
                title: '吃饭',
                isDone: true
            },
            {
                id: nanoid(),
                title: '上分',
                isDone: true
            },
            {
                id: nanoid(),
                title: '敲代码',
                isDone: false
            }
        ]
    }
    addTodo(title) {
        console.log('App title: ', title)
        // 1. 拼接todo
        // 2. 添加到todos数组中
        // 3. 设置状态
        const todo = {
            id: nanoid(),
            title,
            isDone: false
        }
        this.setState({
            todos: [todo, ...this.state.todos]
        })
    }

    // 根据id删除
    deleteItem(id) {
        if (!window.confirm('确定要删除么？')) return;
        console.log('App id: ', id)
        // 将todos中，id是这个id的删除，不是这个id的保留
        this.setState({
            todos: this.state.todos.filter(todo => todo.id !== id)
        })
    }
    // 切换完成状态 
    checkItem(todo) {
        todo.isDone = !todo.isDone
        this.setState({
            todos: [...this.state.todos]
        })
    }
    render() {
        let { todos } = this.state
        return (
            <div className="todo-container">
                <div className="todo-wrap">
                    {/* 改变this指向并传递给子组件 */}
                    <Header addTodo={this.addTodo.bind(this)} />
                    <List todos={todos} deleteItem={this.deleteItem.bind(this)} checkItem={this.checkItem.bind(this)} />
                    <Footer todos={todos} />
                </div>
            </div>
        )
    }
}
